package com.nand.module.function.ui;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.GlideEngine;
import com.nand.library.base.utils.SpUtils;
import com.nand.module.function.R;
import com.nand.module.function.adapter.CheckItemsAdapter;
import com.nand.module.function.bean.CheckItemsBean;
import com.nand.module.function.bean.CheckItemsBeans;
import com.nand.module.function.bean.IqcListBean;
import com.nand.module.function.bean.SamplingBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.view.CommonPopupWindow;
import com.nand.module.function.view.ImageActivity;
import com.nand.module.function.view.WheelView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * created by 86185
 * on 2020/1/2
 * 检验详情与提交
 */
@Route(path = "/function/iqc/checkout")
public class IqcCheckoutActivity extends BaseActivity implements View.OnClickListener {

    private String oid;
    private TextView mHeadLine, mTvJyxx, mTvJyx, mTvWlbm, mTvWlmc, mTvGys, mTvBjzsl, mTvYxj, mTvKf, mTvBz, mTvJybg, mTvCjsl, mTvConfirm, mTvpsl, mTvBeiz;
    private EditText mEtBeiz;
    private LinearLayout mLlJyxx, mLlJyx;
    private CommonPopupWindow window, windowContent;
    private WheelView mWheelview;
    private RecyclerView mRecycler, mJyxRecycler;
    private PublishImgAdapter imgAdapter;
    private ArrayList<String> imgPathList = new ArrayList<>();
    private String fMmMaterialOid;
    private CheckItemsAdapter mJyxAdapter;
    private String checkId;
    private String optimisticLockField;
    private String batchID;
    private HttpParams params;
    private int totalNumber;
    private String partCode;
    private double samplingNumber = 0;
    private int userId, type;
    private TextView horiText, mTvSfmj;
    private CommonPopupWindow.LayoutGravity layoutGravity;
    private ShowImgAdapter imgAdapter2;
    private TextView mTvPdBhg;
    private TextView mTvPdHg;
    private String batchAmount;

    private LinearLayout mLlSfmj;
    private TextView mTvPdMj;
    private TextView mTvBmj;
    private TextView mTvMj;
    private List<String> imageList;
    private ArrayList<String> mData;
    private int isHg = 1;
    private int pdID = 1;
    private String iqcNCheck, checkReport; //是否免检id  优先级id  检验报告
    private int packageReport; //包装id


    @Override
    protected int initLayout() {
        return R.layout.activity_iqc_checkout;
    }

    @Override
    protected void initView() {
        type = getIntent().getIntExtra("type", 1); //0：未检验  1：已检验
        oid = getIntent().getStringExtra("oid"); //oid标识
        userId = SpUtils.readInt(this, "userId", 0);  //用户id

        mHeadLine = findViewById(R.id.tv_headline);
        mTvJyxx = findViewById(R.id.tv_jyxx);
        mTvJyx = findViewById(R.id.tv_jyx);
        mLlJyxx = findViewById(R.id.ll_jyxx);
        mLlJyx = findViewById(R.id.ll_jyx);

        mTvWlbm = findViewById(R.id.tv_wlbm);
        mTvWlmc = findViewById(R.id.tv_wlmc);
        mTvGys = findViewById(R.id.tv_gys);
        mTvBjzsl = findViewById(R.id.tv_bjzsl);
        mTvSfmj = findViewById(R.id.tv_sfmj);
        mTvYxj = findViewById(R.id.tv_yxj);
        mTvKf = findViewById(R.id.tv_kf);
        mTvBz = findViewById(R.id.tv_bz);
        mTvJybg = findViewById(R.id.tv_jybg);
        mTvpsl = findViewById(R.id.tv_psl);
        mTvCjsl = findViewById(R.id.tv_cjsl);
        mTvConfirm = findViewById(R.id.tv_iqc_confirm);

        mLlSfmj = findViewById(R.id.ll_sfmj);
        mTvMj = findViewById(R.id.tv_mj);
        mTvBmj = findViewById(R.id.tv_bmj);
        mTvPdMj = findViewById(R.id.tv_pd_mj);
        mTvPdHg = findViewById(R.id.tv_pd_hg);
        mTvPdBhg = findViewById(R.id.tv_pd_bhg);
        mEtBeiz = findViewById(R.id.et_beiz);
        mTvBeiz = findViewById(R.id.tv_beiz);
        mRecycler = findViewById(R.id.recycler);
        mJyxRecycler = findViewById(R.id.recyclerview);

        mTvJyxx.setOnClickListener(this);
        mTvJyx.setOnClickListener(this);
        mTvConfirm.setOnClickListener(this);

        switch (type) {
            case 0: //已送检
                mHeadLine.setText("检验提交");
                GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
                mRecycler.setLayoutManager(layoutManager);
                mRecycler.setAdapter(imgAdapter);
                imgAdapter = new PublishImgAdapter(this);
                imgAdapter.setImgItemClickListener(new PublishImgAdapter.ImgItemClick() {
                    @Override
                    public void itemClick(String url, int position) {
              /*  // 图片点击 , 可以用大图显示
                Intent intent = new Intent(mContext, ImageActivity.class);
                intent.putExtra(ImageActivity.CURRENT_IMG_URL, url);
                intent.putStringArrayListExtra(ImageActivity.IMG_LIST, imgAdapter.getData());
                startActivity(intent);*/

                        Intent intent1 = new Intent(mContext, ImageActivity.class);
                        //intent1.putExtra(ImageActivity.CURRENT_IMG_URL, imgList.get(0));
                        intent1.putStringArrayListExtra(ImageActivity.IMG_LIST, mData);
                        startActivity(intent1);
                    }

                    @Override
                    public void lastItemClick() {
                        // 添加图片
                        EasyPhotos.createAlbum(IqcCheckoutActivity.this, true, GlideEngine.getInstance())
                                .setFileProviderAuthority("com.nand.library.base")
                                .setCount(3)
                                .start(new SelectCallback() {
                                    @Override
                                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                        for (int i = 0; i < photos.size(); i++) {
                                            imgPathList.add(photos.get(i).path);
                                        }
                                        imgAdapter.setData(imgPathList);
                                    }
                                });

                    }

                    @Override
                    public void delImg(String url, int position) {
                        if (imgAdapter != null) {
                            if (imgPathList.remove(url)) {
                                // 图片数量少于9张, 显示添加图片按钮
                                imgAdapter.setData(imgPathList);
                            }
                        }
                    }
                });
                break;
            case 1: //以检验
                mHeadLine.setText("检验详情");
                mTvConfirm.setVisibility(View.GONE);

                mEtBeiz.setVisibility(View.GONE);
                GridLayoutManager layoutManager2 = new GridLayoutManager(this, 3);
                mRecycler.setLayoutManager(layoutManager2);
                imgAdapter2 = new ShowImgAdapter(this);
                mRecycler.setAdapter(imgAdapter2);
                imgAdapter2.setImgItemClickListener(new ShowImgAdapter.ImgItemClick() {
                    @Override
                    public void itemClick(String url, int position) {
                        Intent intent1 = new Intent(mContext, ImageActivity.class);
                        //intent1.putExtra(ImageActivity.CURRENT_IMG_URL, imgList.get(0));
                        intent1.putStringArrayListExtra(ImageActivity.IMG_LIST, mData);
                        startActivity(intent1);
                    }

                    @Override
                    public void lastItemClick() {

                    }

                    @Override
                    public void delImg(String url) {

                    }
                });
                break;
        }
        mJyxRecycler.setLayoutManager(new LinearLayoutManager(this));
        mJyxAdapter = new CheckItemsAdapter(this);
        mJyxRecycler.setAdapter(mJyxAdapter);
        mJyxAdapter.setOnItemClickListener(new CheckItemsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onJcnrClick(int position, String context, TextView textView) {
                layoutGravity = new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.ALIGN_LEFT | CommonPopupWindow.LayoutGravity.TO_BOTTOM);
                layoutGravity.setHoriGravity(CommonPopupWindow.LayoutGravity.ALIGN_RIGHT);
                layoutGravity.setVertGravity(CommonPopupWindow.LayoutGravity.TO_BOTTOM);
                windowContent.showBashOfAnchor(textView, layoutGravity, 0, 0);
                horiText.setText(context);
            }

            @Override
            public void onRadioClick(List<CheckItemsBean> list) {

                if ("1".equals(iqcNCheck)) {
                    for (int i = 0; i < list.size(); i++) {
                        String s = list.get(i).toString();
                        if (0 == list.get(i).getResult()) {
                            isHg = 0;

                        }
                    }
                    if (1 == isHg) {
                        pdID = 1;
                        initShowTab(mTvPdHg, mTvPdBhg, null);
                    } else {
                        isHg = 1;
                        initShowTab(mTvPdBhg, mTvPdHg, null);
                        pdID = 0;
                    }
                }


            }
        });
        windowContent = new CommonPopupWindow(this, R.layout.item_show_content, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initView() {
                View view = getContentView();
                horiText = view.findViewById(R.id.hori_text);
            }

            @Override
            protected void initEvent() {
            }
        };
    }

    @Override
    protected void initData() {
        HttpParams params = new HttpParams();
        params.put("oid", oid);
        OkGoUtils.getInstance().post(this, URL.IQC_PECTION_LIST, params, 1, true, mCallback);
    }

    /**
     * 请求返回的处理
     */
    private MyCallback mCallback = new MyCallback() {
        @Override
        public void onSuccess(ResponseBean response, int id) {
            switch (id) {
                case 1:
                    String s = response.getDataInfo().toString();
                    IqcListBean listBeans = JSON.parseObject(s, IqcListBean.class);
                    List<IqcListBean.DataListBean> dataList = listBeans.getDataList();

                    LogUtils.e("dataaaaaa=========="+s);
                    if (0 < dataList.size()) {
                        fMmMaterialOid = dataList.get(0).getfMmMaterialOid();
                        IqcListBean.DataListBean bean = dataList.get(0);
                        oid = bean.getOid();
                        checkId = bean.getCheckId();
                        optimisticLockField = bean.getOptimisticLockField();
                        batchID = bean.getBatchID();
                        totalNumber = bean.getTotalNumber();

                        partCode = bean.getPartCode();
                        mTvWlbm.setText(partCode);
                        mTvWlmc.setText(bean.getPartName());
                        mTvGys.setText(bean.getSupplierName());
                        mTvBjzsl.setText(totalNumber + "");
                        iqcNCheck = bean.getIqcNCheck();
                        mTvYxj.setText(bean.getPriority());
                        mTvKf.setText(bean.getStoreName());
                        packageReport = bean.getPackageReport();
                        checkReport = bean.getCheckReport();
                        batchAmount = bean.getBatchAmount();
                        mTvpsl.setText(batchAmount);
                        initCjsl(); //获取抽检数量
                        switch (iqcNCheck) {
                            case "0":  // 免检
                                pdID = 2;
                                mTvSfmj.setText("免检");
                                mTvPdMj.setVisibility(View.VISIBLE);
                                mLlSfmj.setVisibility(View.VISIBLE);
                                initShowTab(mTvMj, mTvBmj, null);
                                initShowTab(mTvPdMj, mTvPdHg, mTvPdBhg);
                                mTvMj.setOnClickListener(IqcCheckoutActivity.this);
                                mTvBmj.setOnClickListener(IqcCheckoutActivity.this);
                                break;
                            case "1": //不免检
                                pdID = 1;
                                mTvSfmj.setText("不免检");
                                mLlSfmj.setVisibility(View.GONE);
                                mTvPdMj.setVisibility(View.GONE);
                                initShowTab(mTvPdHg, mTvPdBhg, null);
                                break;
                        }

                        if (0 == packageReport) {  //包装
                            mTvBz.setText("不完整");
                        } else {
                            mTvBz.setText("完整");
                        }

                        if ("0".equals(checkReport)) {  //检验报告
                            mTvJybg.setText("不完整");
                        } else {
                            mTvJybg.setText("完整");
                        }


                        switch (type) {
                            case 0: //未检验
                                HttpParams params = new HttpParams();
                                params.put("fMmMaterialOid", fMmMaterialOid);
                                OkGoUtils.getInstance().post(IqcCheckoutActivity.this, URL.IQC_STAND_LIST, params, 3, true,mCallback);
                                break;
                            case 1:  //已检验
                                mTvCjsl.setText(bean.getSpotCheck()); //抽检数量
                                mTvMj.setClickable(false);
                                mTvBmj.setClickable(false);

                                List<CheckItemsBean> checkResult = bean.getCheckResult();
                                mList.clear();
                                for (CheckItemsBean bea : checkResult) {
                                    mList.add(bea);
                                }
                                mJyxAdapter.setData(mList, type);
                                mTvBeiz.setText(bean.getMemo());

                                int iqcResult = bean.getIqcResult();
                                switch (iqcResult) {
                                    case 0:
                                        initShowTab(mTvPdBhg, mTvPdHg, mTvPdMj);
                                        initShowTab(mTvBmj,mTvMj,null);
                                        break;
                                    case 1:
                                        initShowTab(mTvBmj,mTvMj,null);
                                        initShowTab(mTvPdHg, mTvPdBhg, mTvPdMj);
                                        break;
                                    case 2:
                                        initShowTab(mTvPdMj, mTvPdHg, mTvPdBhg);
                                        initShowTab(mTvMj,mTvBmj,null);
                                        break;
                                }

                                imageList = bean.getImageList();
                                if ("".equals(imageList) || null == imageList) {
                                    return;
                                }

                                mData = new ArrayList<>();
                                for (int i = 0; i < imageList.size(); i++) {
                                    mData.add(i, imageList.get(i));
                                }
                                imgAdapter2.setData(mData);
                                break;
                        }

                    }
                    break;
                case 2:
                    showToast("提交成功");
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case 3:
                    String data = response.getDataInfo().toString();
                    CheckItemsBeans listBeans3 = JSON.parseObject(data, CheckItemsBeans.class);
                    List<CheckItemsBean> dataList3 = listBeans3.getDataList();

                    mList.clear();
                    for (CheckItemsBean bean : dataList3) {
                        mList.add(bean);
                    }

                    if ("0".equals(iqcNCheck)) { //免检
                        mJyxAdapter.setData(mList, 2);
                    } else  if ("1".equals(iqcNCheck)) { //不免检
                        mJyxAdapter.setData(mList, type);
                    }

                    break;
            }

        }

        @Override
        public void onError(Throwable e, int id) {
        }
    };

    private void initCjsl() {
        HttpParams params2 = new HttpParams();
        params2.put("partId", partCode); //物料编码
        params2.put("number", totalNumber); //总数量
        params2.put("batchAmount", batchAmount); //批数量
        OkGoUtils.getInstance().post(IqcCheckoutActivity.this, URL.GET_SAMPLING_NUMBER, params2, 0, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (200 == response.getCode()) {
                    String s1 = response.getDataInfo().toString();
                    SamplingBean bean = JSON.parseObject(s1, SamplingBean.class);
                    samplingNumber = bean.getSamplingNumber();
                    mTvCjsl.setText(String.valueOf(samplingNumber));
                } else {
                    showToast("抽检数量获取失败");
                }
            }

            @Override
            public void onError(Throwable e, int id) {
                showToast("抽检数量获取失败");
            }
        });
    }

    private List<CheckItemsBean> mList = new ArrayList<>();
    private int jyxSelect = 0;
    private int whether = 0;
    private int whether2 = 0;

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_jyxx) {
            mTvJyxx.setBackgroundColor(getResources().getColor(R.color.color_1a0077f7));
            mTvJyx.setBackgroundColor(getResources().getColor(R.color.white));
            mLlJyxx.setVisibility(View.VISIBLE);
            mLlJyx.setVisibility(View.GONE);
            mTvJyxx.setTextColor(getResources().getColor(R.color.color_33));
            mTvJyx.setTextColor(getResources().getColor(R.color.color_99));
        } else if (id == R.id.tv_jyx) {
            mTvJyx.setBackgroundColor(getResources().getColor(R.color.color_1a0077f7));
            mTvJyxx.setBackgroundColor(getResources().getColor(R.color.white));
            mLlJyx.setVisibility(View.VISIBLE);
            mLlJyxx.setVisibility(View.GONE);
            mTvJyx.setTextColor(getResources().getColor(R.color.color_33));
            mTvJyxx.setTextColor(getResources().getColor(R.color.color_99));
        } else if (id == R.id.tv_mj) {  //免检
            iqcNCheck = "0";
            mTvPdMj.setVisibility(View.VISIBLE);
            pdID = 2;
            initShowTab(mTvMj, mTvBmj, null);
            initShowTab(mTvPdMj, mTvPdBhg, mTvPdHg);
            mTvPdMj.setVisibility(View.VISIBLE);
            mJyxAdapter.setData(mList, 2);
        } else if (id == R.id.tv_bmj) {  //不免检
            mJyxAdapter.setData(mList, 0);
            iqcNCheck = "1";
            mTvPdMj.setVisibility(View.GONE);
            pdID = 1;
            initShowTab(mTvBmj, mTvMj, null);
            initShowTab(mTvPdHg, mTvPdBhg, null);
            mTvPdMj.setVisibility(View.GONE);
            mJyxAdapter.setData(mList, 0);
        } else if (id == R.id.tv_iqc_confirm) {
            List<CheckItemsBean> checkItemsBean = mJyxAdapter.getCheckItemsBean();
            for (int i = 0; i < checkItemsBean.size(); i++) {
                String result = checkItemsBean.get(i).getIqcCheckContentResult();
                if (!"".equals(result)) {
                    whether = 1;
                }
                if (2 != checkItemsBean.get(i).getResult()){
                    whether2 = 1;
                }
                if (2 == pdID){
                    checkItemsBean.get(i).setResult(2);
                    checkItemsBean.get(i).setIqcCheckContentResult("");
                }
            }
            if (0 == whether && mList.size() > 0 && 2 != pdID) {
                showToast("请至少输入一个实测值");
                return;
            }else {
                whether = 0;
            }
            if (0== whether2 &&  mList.size() > 0 && 2 != pdID){
                showToast("请至少点击一个合/不合格");
                return;
            }else {
                whether2 = 0;
            }
            final String tabJson = JSON.toJSONString(checkItemsBean);

            final String beiz = mEtBeiz.getText().toString();

            params = new HttpParams();
            params.put("batchId", batchID);  //物料批次码
            params.put("checkId", checkId);  //检验单据号
            params.put("spotCheck", samplingNumber);  //抽检数量
            params.put("batchAmount", batchAmount);  //批数量
            params.put("oid", oid);  //
            params.put("userId", userId);  //
            params.put("iqcResult", pdID);  //IQC结果判定 0不合格 1合格 2免检
            params.put("memo", beiz);  //备注
            params.put("optimisticLockField", optimisticLockField);  //互锁效验
            params.put("jsonData", tabJson); //IQC检查项集合

            LogUtils.e("dataaaaaa=========" + tabJson);
            LogUtils.e("dataaaaaa=========" + pdID);

            ArrayList<File> files = new ArrayList<>();
            if (imgPathList.size() > 0) {
                for (int i = 0; i < imgPathList.size(); i++) {
                    File file = new File(imgPathList.get(i));
                    files.add(file);
                }
                OkGoUtils.getInstance().upload(this, URL.UPLOAD_PICTURES, files, new MyCallback() {
                    @Override
                    public void onSuccess(ResponseBean response, int id) {
                        String imagePath = "";
                        if (response.getCode() == 200) {
                            LogUtils.e("data===========" + response.getDataInfo().toString());
                            List<String> list = JSON.parseArray(response.getDataInfo().toString(), String.class);
                            for (int i = 0; i < list.size(); i++) {
                                if (i == list.size()) {
                                    imagePath += list.get(i);
                                } else {
                                    imagePath += list.get(i) + ",";
                                }
                            }
                            LogUtils.e("2ac===========" + imagePath);
                            Log.e("onSuccess", imagePath);

                            params.put("imagePath", imagePath); //图片 多张图片逗号隔开
                                  OkGoUtils.getInstance().post(IqcCheckoutActivity.this, URL.SUBMIT_IQC_RESULT, params, 2, true, mCallback);
                        } else {
                            showToast(response.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {

                    }
                });
            } else {
                params.put("imagePath", ","); //图片 多张图片逗号隔开
                   OkGoUtils.getInstance().post(IqcCheckoutActivity.this, URL.SUBMIT_IQC_RESULT, params, 2, true, mCallback);
            }
        }
    }

    private void initShowTab(TextView one, TextView two, TextView three) {
        if (one != null) {
            one.setBackgroundResource(R.drawable.m_border_13_blue);
            one.setTextColor(getResources().getColor(R.color.blue2));
        }
        if (two != null) {
            two.setBackgroundResource(R.drawable.m_border_13_99);
            two.setTextColor(getResources().getColor(R.color.color_99));
        }
        if (three != null) {
            three.setBackgroundResource(R.drawable.m_border_13_99);
            three.setTextColor(getResources().getColor(R.color.color_99));
        }
    }
}
